import axios, {  AxiosResponse, InternalAxiosRequestConfig } from 'axios';
// 底层库不去依赖任何业务库，这里改成第三方库
// import { Message } from '@arco-design/web-react';
// import { MessageManager } from '@utils/MessageManager';


const http = axios.create({
    headers: {
        'Content-Type': 'application/json; charset=utf-8',
    },
});

let token = '';
const getToken = () => {
    try {
        token = localStorage.getItem('token') || '';
        return token || '';
    } catch (e) {
        return '';
    }
};
/* 请求拦截器 */
http.interceptors.request.use(
    (config: InternalAxiosRequestConfig) => {
        if (config?.headers?.Authorization == null) {
            const authToken = getToken();

            if (authToken) {
                config.headers.Authorization = authToken;
            }
        }

        return config;
    },
    (error) => {
        return Promise.reject(error);
    }
);

http.interceptors.response.use(
    (resp: AxiosResponse) => {
        // http 状态码处理，如果不是200则都是服务器异常
        switch (resp.status) {
            case 200: {
                if (resp.data) {
                    // 处理特殊的状态码
                    switch (resp.data.code) {
                        case 0: {
                            return resp.data;
                        }
                        case 401: {
                            break;
                        }
                        default: {
                            return resp.data;
                        }
                    }
                    return resp.data;
                } else {
                    return resp;
                }
            }
            case 401: {
                // const location = useLocation();
                // window.location.protocol + '//' + window.location.host + location.pathname;
                // window.location.href = window.location.origin + '/login';
                // navigate('/login', {});
                break;
            }
            default: {
                // Message.error({
                //     content: '请求失败：服务器异常（' + resp.status + '）',
                // });
                break;
            }
        }
    },
    (error) => {
        const pMsg = {
            origin: window.location.href,
            code: error.response?.status || 500,
            message: 'axios 拦截请求错误',
            data: error,
        };
        // MessageManager.getInstance().setData(pMsg);
        // MessageManager.getInstance().emit('message', pMsg);
        return Promise.reject(error);
    }
);

export default http;
